package servlet;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import entity.Review;
import org.json.JSONArray;
import service.OrderService;
import service.ReviewService;

@WebServlet("/ReviewServlet")
public class ReviewServlet extends HttpServlet {
    private ReviewService reviewService = new ReviewService();
    private OrderService orderService = new OrderService();

//    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding("UTF-8");
//        response.setCharacterEncoding("UTF-8");
//
//        // 获取请求参数中的产品ID
//        String productIdStr = request.getParameter("productId");
//        if (productIdStr == null || !productIdStr.matches("\\d+")) {
//            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid product ID");
//            return new ArrayList<>();
//        }
//
//        int productId = Integer.parseInt(productIdStr);
//
//        // 调用ReviewDao的方法获取评论
//        ReviewService reviewDao = new ReviewService();
//        List<Review> reviews = reviewDao.queryReviewsByProductId(productId);
//        return reviews;
//    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应类型为 JSON
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 获取请求的 JSON 数据
        StringBuilder requestData = new StringBuilder();
        String line;
        while ((line = request.getReader().readLine()) != null) {
            requestData.append(line);
        }

        try {
            // 解析 JSON 数据
            JSONArray reviews = new JSONArray(requestData.toString());
            HashMap<String,String> user =  (HashMap<String, String>) request.getSession().getAttribute("user");
            int userId = 0;
            if(user==null){

            }else{
                userId = Integer.parseInt(user.get("userId"));// 从会话中获取用户ID
            }
            // 调用服务层处理数据
            boolean success = reviewService.submitReview(reviews,userId);

            // 返回响应结果
            if (success) {
                int orderId = Integer.parseInt(request.getParameter("orderId"));
                orderService.updateOrderStatus(orderId,"已评价");
                out.print("{\"status\": \"success\", \"message\": \"评价提交成功！\"}");
            } else {
                out.print("{\"status\": \"error\", \"message\": \"评价提交失败！\"}");
            }
        } catch (Exception e) {
            // 捕获 JSON 解析或其他错误
            out.print("{\"status\": \"error\", \"message\": \"处理请求时出现错误！\"}");
            e.printStackTrace();
        }
    }
}
